<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
  >
    <el-form-item label="用户名" prop="name">
      <el-input v-model="ruleForm.name" type="text" autocomplete="off" />
    </el-form-item>
    <el-form-item label="密码" prop="pwd">
      <el-input v-model="ruleForm.pwd" type="password" autocomplete="off" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >Submit</el-button
      >
    </el-form-item>
  </el-form>
</template>
  
  <script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { login } from "../../api/api";
import { useRouter } from "vue-router";
import Cache from "../../utils/cache/cache";
import { useUser } from "../../stores/user";

const router = useRouter();

const userUsers = useUser();

const ruleFormRef = ref<FormInstance>();

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    if (ruleForm.pwd !== "") {
      if (!ruleFormRef.value) return;
    }
    callback();
  }
};

const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入用户名"));
  } else {
    if (ruleForm.name !== "") {
      if (!ruleFormRef.value) return;
    }
    callback();
  }
};

const ruleForm = reactive({
  name: "",
  pwd: "",
});

const rules = reactive<FormRules>({
  pwd: [{ validator: validatePass, trigger: "blur" }],
  name: [{ validator: validatePass2, trigger: "blur" }],
});

// 点击登录时执行的函数
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      userUsers.loginAction(ruleForm);
      router.push("/index");
    } else {
      console.log("error submit!");
      return false;
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>